package com.jerry.activeMq.impl;

import com.jerry.activeMq.JerryProvider;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by jerry on 2016/12/17.
 */
public class JerryProviderImpl implements JerryProvider {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;

    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;

    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;
    private

    //factor
            ConnectionFactory connectionFactory;

    //connection
    Connection connection;

    //session
    Session session;

    ThreadLocal<MessageProducer> producerThreadLocal = new ThreadLocal<MessageProducer>();

    ThreadLocal<Integer> integerThreadLocal = new ThreadLocal<Integer>();


    @Override
    public void init() {
        connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
        try {
            connection = connectionFactory.createConnection();

            connection.start();

            session = connection.createSession(true, Session.SESSION_TRANSACTED);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void SendMessage(String desName) {
        try {
            Queue queue = session.createQueue(desName);

            MessageProducer producer = null;

            if (producerThreadLocal.get() != null) {
                producer = producerThreadLocal.get();
            } else {
                producer = session.createProducer(queue);
                producerThreadLocal.set(producer);
            }

            for (int i = 0; i < 1000; i++) {
                Integer count = integerThreadLocal.get();
                if (count == null) {
                    count = 0;
                }
                count += 1;
                TextMessage message = session.createTextMessage(Thread.currentThread().getName() + "prodiver:我是jerry,我向queue队列发送了一条消息" + count);
                producer.send(message);
                System.out.println(Thread.currentThread().getName() + "prodiver:我是jerry,我向queue队列发送了一条消息" + count);
                integerThreadLocal.set(count);
            }
            session.commit();
        } catch (JMSException e) {
            e.printStackTrace();
        }

    }
}
